"use strict";

const { Controller } = require("egg");
const OSS = require("ali-oss");

class Oss extends Controller {
    /**
     * @api {GET} /x/v1/common/oss/stsDispatcher 01:派发OSS临时密钥接口
     * @apiGroup 01:OSS接口
     * @apiVersion 1.0.0
     * @apiSuccess {string} code 10101
     * @apiSuccess {string} data 临时密钥
     */
    async dispatchSTS() {
        // 实例化sts
        const sts = new OSS.STS({
            accessKeyId: this.config.STS.accessKeyId,
            accessKeySecret: this.config.STS.accessKeySecret,
        });
        const { credentials } = await sts.assumeRole(this.config.RamRole.uploader);
        const str = `${credentials.AccessKeyId.replace("STS.", "")}.${credentials.AccessKeySecret}.${credentials.SecurityToken.replace("==", "")}`.split("").reverse().join("");
        this.ctx.returnBody(10101, "", str);
    }
    /**
     * @api {GET} /x/v1/common/oss/simpleUploader 02:服务器简单上传接口
     * @apiGroup 01:OSS接口
     * @apiVersion 1.0.0
     * @apiSuccess {number} code 10102
     * @apiSuccess {string} data 文件地址
     * @apiError {number} code 10086
     */
    async simpleUploader() {
        const { ctx } = this;
        const [ file ] = this.ctx.request.files;
        const dir = ctx.request.header.dir || ctx.request.body.dir;
        const body = ctx.request.header.body || ctx.request.body.body;
        const url = ctx.request.header.url || ctx.request.body.url;

        if (!file || !dir || !url) {
            ctx.returnBody(10086, "");
            return;
        }

        const result = await ctx.service.oss.ossSimpleUploadService(file, dir, url, body);
        ctx.body = { code: 10102, message: "", file_path: result.url, object: result.name };
    }
}

module.exports = Oss;
